package gm.server.virtual.simulator2D;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import static java.awt.image.ImageObserver.ALLBITS;

public class ImageToBufferedImage {

    static BufferedImage image;
    static boolean imageLoaded = false;

    public static BufferedImage convert(final Image sourceImage) {

        ImageObserver myImageObserver = (Image image1, int flags, int x, int y, int width, int height) -> {
            if ((flags & ALLBITS) != 0) {
                
                imageLoaded = true;
                
                System.out.println("Image loading finished!");
                
                return false;
                
            }

            return true;
        };

        sourceImage.getWidth(myImageObserver);

        while (!imageLoaded) {
        }

        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();

        GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();
        image = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null), sourceImage.getHeight(null), Transparency.BITMASK);

        Graphics graphics = image.createGraphics();
        graphics.drawImage(sourceImage, 0, 0, null);
        graphics.dispose();

        return image;

    }

    /**
     * To draw on the screen, it is first necessary to subclass a Component and
     * override its paint() method. The paint() method is automatically called
     * by the windowing system whenever component's area needs to be repainted.
     */
    static class CustomPaintComponent extends Component {

        @Override
        public void paint(Graphics g) {

            Graphics2D g2d = (Graphics2D) g;
            int x = 0;
            int y = 0;
            g2d.drawImage(image, x, y, this);

        }

    }

}
